package com.zhiyi.coco.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.zhiyi.coco.entity.SysLoginInfo;
import com.zhiyi.coco.entity.SysUser;
import com.zhiyi.coco.service.SysLoginInfoService;
import com.zhiyi.coco.service.SysUserService;
import com.zhiyi.coco.tools.CoCoFileUpload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Api(value = "SysUserController", description = "对用户信息的操作")
@RestController
@RequestMapping("/user")
@Log4j
public class SysUserController {
    @Autowired
    private SysUserService service;
    @Autowired
    private SysLoginInfoService loginInfoService;

    @ApiOperation("登录验证")
    @ResponseBody
    @RequestMapping("/success/{logincode}/{pwd}")
    public String l(@PathVariable String logincode, @PathVariable String pwd, HttpSession session) {
        SysUser loginBycode = service.loginByCode(logincode, pwd);
        SysUser login = service.login(loginBycode);
//        user=service.login(user);
//        log.info(user.getPassword());
        if (login != null) {
            session.setAttribute("user", login);
            return "index";
        }
        return "login";
    }

    /**
     * @return 所有用户信息
     */
    @ApiOperation("查询所有用户信息")
    @ResponseBody
    @RequestMapping("/getAllUsers")
    public List<SysUser> getAllUsers() {
        List<SysUser> list = service.getAllUsers();
        return list;
    }

    /**
     * @return 根据用户编号获取用户信息
     */
    @ApiOperation("根据用户编号获取用户信息")
    @ResponseBody
    @RequestMapping("/getInfoById/{id}")
    public SysUser getInfoById(@PathVariable Integer id) {
        SysUser user = service.getInfoById(id);
        if(user==null){
            return null;
        }
        return user;
    }

    /**
     * @return 根据用户编号删除用户信息
     */
    @ApiOperation("根据用户编号删除用户信息")
    @ResponseBody
    @RequestMapping("/deleteInfoById/{id}")
    public boolean deleteInfoById(@PathVariable Integer id) {
        Integer i = service.deleteInfoById(id);
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 登录
     *
     * @return
     */
    @ApiOperation("登录验证")
    @ResponseBody
    @PostMapping(value = "/success/{logincode}/{pwd}")
    public String login(@PathVariable String logincode, @PathVariable String pwd, HttpSession session) {
        SysUser loginBycode = service.loginByCode(logincode, pwd);
        SysUser login = service.login(loginBycode);
        if (login != null) {
            //如果存在，保存用户数据，跳转回开发者界面
            session.setAttribute("user", login);
            return "foodsmanager";
        }
        return "loginfalse";
    }

    /**
     * @return 根据id删除图片路径
     */
    @ApiOperation("根据用户编号修改用户信息")
    @ResponseBody
    @RequestMapping("/updateimgbyid/{id}")
    public Boolean updateimgbyid(@PathVariable Integer id) {
        Integer i = service.updateimgbyid(id);
        if (i > 0) {
            return true;
        }
        return false;
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("退出登录")
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "login";
    }

    @ApiOperation("修改指定用户信息")
    @RequestMapping(value = "/updateInfo/{yhm}/{username}/{password}/{sex}/{age}/{phone}/{job}/{address}/{logoPicPath}/{modifyid}", method = RequestMethod.POST)
    public Boolean addImg(@PathVariable String yhm, @PathVariable String username,
                          @PathVariable String password, @PathVariable String sex,
                          @PathVariable Integer age, @PathVariable String phone,
                          @PathVariable Integer job, @PathVariable String address,
                          @PathVariable String logoPicPath,
                          @PathVariable Integer modifyid, HttpServletRequest request, MultipartFile attach) {
        HashMap<String, Object> file = new HashMap<String, Object>();
        if (!CoCoFileUpload.fileUpload(attach, request, file)) {
            return false;
        }
        SysUser su = new SysUser();
        su.setUsername(username);
        su.setPassword(password);
        su.setSalt(SecureUtil.md5(password + "abc"));
        SysLoginInfo loginInfo = new SysLoginInfo();
        loginInfo.setUid(modifyid);
        loginInfo.setName(yhm);
        loginInfo.setSex(sex);
        loginInfo.setAge(age);
        loginInfo.setPhone(phone);
        loginInfo.setAddress(address);
        loginInfo.setImg(logoPicPath);
        loginInfo.setJobId(job);
        try {
            if (service.updateByPrimaryKeySelective(su) == 1) {
                if (loginInfoService.updateByPrimaryKeySelective(loginInfo) == 1) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        if (attach.isEmpty()) {
//            System.out.println("文件为空空");
//        }
//        String fileName = attach.getOriginalFilename();  // 文件名
//        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
//        String filePath = "D://temp-rainy//"; // 上传后的路径
//        fileName = UUID.randomUUID() + suffixName; // 新文件名
//        File dest = new File(filePath + fileName);
//        if (!dest.getParentFile().exists()) {
//            dest.getParentFile().mkdirs();
//        }
//        try {
//            attach.transferTo(dest);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String filename = fileName;
        return false;
    }

    @ApiOperation("修改指定用户信息")
    @PostMapping("/updateInfo2")
    public Object addImg2(SysLoginInfo loginInfo, SysUser user) {
        System.out.println(JSON.toJSONString(loginInfo));
        System.out.println(JSON.toJSONString(user));
        user.setSalt(SecureUtil.md5(user.getPassword() + "abc"));
        user.setUpdateTime(new Date());
        if (service.updateByPrimaryKeySelective(user) == 1) {
            if (loginInfoService.updateByPrimaryKeySelective(loginInfo) == 1) {
                return true;
            }
        }
        return false;
    }

    @ApiOperation("添加用户")
    @PostMapping("/addInfo")
    public Object add(SysLoginInfo loginInfo,SysUser user){
//        System.out.println(JSON.toJSONString(loginInfo));
        System.out.println(JSON.toJSONString(user));
        user.setSalt(SecureUtil.md5(user.getPassword() + "abc"));
        user.setUpdateTime(new Date());
        if (service.insertSelective(user) == 1) {
            if (loginInfoService.insertSelective(loginInfo) == 1) {
//                loginInfo.setUid(loginInfo.getId());
//                loginInfo.setJobId(loginInfo.getJobId());
                return true;
            }
        }
        return false;
    }
    @ApiOperation("")
    @PostMapping("/selectByname1/{name}")
    public SysLoginInfo selectByname1(@PathVariable String name ){
        SysLoginInfo loginInfo=loginInfoService.selectByname(name);
        return loginInfo ;
    }

    /**
     * @return 根据id修改数据
     */
    @ApiOperation("根据用户编号修改用户信息")
    @ResponseBody
    @RequestMapping("/updateuId/{id}")
    public Integer updateuId(@PathVariable Integer id) {
        Integer i = service.updateuId(id);
        return i;
    }

}
